/*
 * Event.cpp
 *
 * Copyright 2012 Fabian Wenzelmann, Nikolaus Mayer
 *
 * This file is part of ss12-gtprojects.
 *
 * ss12-gtprojects is free software: you
 * can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * ss12-gtprojects is distributed in the hope
 * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
 * Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ss12-gtprojects.
 *
 * If not, see <http://www.gnu.org/licenses/>.
 */

#include "NFGParser.h"

#include <cstdlib>

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

#include "Event.h"
#include "Player.h"
#include "StrategicGame.h"

NFGParser::NFGParser() {}

NFGParser::~NFGParser() { }

StrategicGame* NFGParser::parseGame(std::string &in) {
    std::string line;
    // 0: read NFG 1 R
    size_t pos = in.find('"');
    size_t nextQuote = in.find('"', pos + 1);
    std::string name = in.substr(pos + 1, nextQuote - pos - 1);
    std::cout << "Name " << name << std::endl;
    StrategicGame *game = new StrategicGame(name);
    std::vector<std::string> playerStrings;
    parseStringList(in, &pos, playerStrings);

    for (std::vector<std::string>::const_iterator it = playerStrings.begin();
         it != playerStrings.end();
         it++) {
        Player *p = new Player(*it);
        game->addPlayer(p);
    }
    pos = in.find('{', pos) + 1;
    std::string intermediate;
    size_t open;
    size_t closed;
    do {
        std::vector<std::string> actionStrings;
        parseStringList(in, &pos, actionStrings);
        for (std::vector<std::string>::const_iterator it = actionStrings.begin();
             it != actionStrings.end();
             it++) {
            std::cout << *it << std::endl;
        }
        open = in.find('{', pos);
        closed = in.find('}', pos);
    } while (closed >= open && open != std::string::npos);

    return NULL;
}

void NFGParser::parseStringList(std::string &str, size_t *pos,
                                std::vector<std::string> &result) {
    *pos = str.find('{', *pos);
    (*pos)++;
    size_t end = str.find('}', *pos);
    // find next ""
    while (*pos < end) {
        size_t nextQuote = str.find('"', *pos);
        if (nextQuote == std::string::npos || nextQuote >= end) {
            break;
        }
        size_t endingQuote = str.find('"', nextQuote + 1);
        std::string nextStr = str.substr(nextQuote + 1, endingQuote - nextQuote - 1);
        *pos = endingQuote + 1;
        result.push_back(nextStr);
    }
    *pos = end + 1;
}
